package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.DaoBlog;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {
   private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //约定前后端交互
        //编写后端代码
        //编写前端代码
        //1.前端发送post请求
        //2.接收前端传来的body
        HttpSession session = req.getSession(false);

        req.setCharacterEncoding("utf8");

        Blog blog = objectMapper.readValue(req.getInputStream(), Blog.class);
        //3.解析body然后插入数据库
        DaoBlog daoBlog = new DaoBlog();
        if(blog.getContent() == null || blog.getTitle() == null || blog.getContent().equals("") || blog.getTitle().equals("")){
            resp.setStatus(403);
            return;
        }
        //获取登录用户信息
        User user = (User)session.getAttribute("user");
        //获取登录用户的id
        blog.setUserId(user.getUserId());
        daoBlog.insert(blog);
        resp.setStatus(200);
    }
}
